<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 1、导入mapbox的依赖 -->
    <script src='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js'></script>
    <link href='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css' rel='stylesheet' />
    <style>
        * {
            margin: 0;
            padding: 0
        }

        #map {
            width: 100vw;
            height: 100vh;
        }

        #btn {
            width: 200px;
            height: 50px;
            position: fixed;
            top: 20px;
            right: 50px;
            z-index: 1000;
        }
    </style>
</head>

<body>
    <button id="btn" onclick="clearMap()">清除</button>
    <!-- 2、设置地图容器的挂载点 -->
    <div id="map">

    </div>
    <script>
        /* token */
        mapboxgl.accessToken = 'pk.eyJ1IjoiZXJpYzA5MTciLCJhIjoiY2x3cTI2Zzg0MWY2dDJqcWVpdDI1MHNpcCJ9.k9gLW7ZgLyISNdYHIEEGdQ'
        const map = new mapboxgl.Map({
            /* target-ol */
            container: 'map', // container ID
            /* style-layers */
            style: 'mapbox://styles/mapbox/streets-v12', // style URL
            center: [114.30, 30.50], // starting position [lng, lat]
            zoom: 12, // starting zoom
        });
        map.on("click", evt => {
            var { lng, lat } = evt.lngLat;
            let center = [lng, lat];
            map.addLayer({
                id: "@POINT" + Date.now(),
                source: {
                    type: "geojson",
                    data: {
                        type: "Feature",
                        geometry: {
                            type: "Point",
                            coordinates: center
                        }
                    }
                },
                type: "circle",
                paint: {
                    'circle-radius': 15,
                    'circle-color': "#ff2d51"
                }
            })
        })
        var str = "hello world";
        // str.startsWith()
        function clearMap() {
            /* 1、获取所有的图层 */
            var layers = map.getStyle().layers;
            /* 2、在里面获取以@POINT开头的图层 */
            var arr = layers.filter(item => item.id.startsWith('@POINT'))
            console.log(arr)

            /* 3、根据id值执行删除 */
            arr.forEach(item => {
                map.removeLayer(item.id);
            })
        }
    </script>
</body>

</html>